from rest_framework import viewsets, status
from rest_framework.decorators import action, api_view, permission_classes
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth.models import User
from .models import Host, HostGroup, Project, Environment, UserGroup
from .serializers import (
    HostSerializer, HostGroupSerializer, ProjectSerializer,
    EnvironmentSerializer, UserSerializer, UserGroupSerializer
)
from .host_info import get_host_info


class HostViewSet(viewsets.ModelViewSet):
    """主机管理"""
    queryset = Host.objects.all()
    serializer_class = HostSerializer

    @action(detail=True, methods=['post'])
    def test_connection(self, request, pk=None):
        """测试SSH连接"""
        host = self.get_object()
        try:
            import paramiko
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            
            if host.private_key:
                from io import StringIO
                key = paramiko.RSAKey.from_private_key(StringIO(host.private_key))
                ssh.connect(
                    hostname=host.ip_address,
                    port=host.port,
                    username=host.username,
                    pkey=key,
                    timeout=5
                )
            else:
                ssh.connect(
                    hostname=host.ip_address,
                    port=host.port,
                    username=host.username,
                    password=host.password,
                    timeout=5
                )
            
            ssh.close()
            return Response({'status': 'success', 'message': '连接成功'})
        except Exception as e:
            return Response({'status': 'error', 'message': str(e)}, status=status.HTTP_400_BAD_REQUEST)


class HostGroupViewSet(viewsets.ModelViewSet):
    """主机组管理"""
    queryset = HostGroup.objects.all()
    serializer_class = HostGroupSerializer


class ProjectViewSet(viewsets.ModelViewSet):
    """项目管理"""
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer


class EnvironmentViewSet(viewsets.ModelViewSet):
    """环境管理"""
    queryset = Environment.objects.all()
    serializer_class = EnvironmentSerializer


class UserViewSet(viewsets.ModelViewSet):
    """用户管理"""
    queryset = User.objects.all()
    serializer_class = UserSerializer


class UserGroupViewSet(viewsets.ModelViewSet):
    """用户组管理"""
    queryset = UserGroup.objects.all()
    serializer_class = UserGroupSerializer


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def fetch_host_info(request):
    """
    自动获取主机信息
    通过SSH连接获取主机的操作系统、CPU、内存、磁盘信息
    """
    ip_address = request.data.get('ip_address')
    port = request.data.get('port', 22)
    username = request.data.get('username')
    password = request.data.get('password', '')
    private_key = request.data.get('private_key', '')
    
    if not all([ip_address, username]):
        return Response({
            'success': False,
            'error': '请提供IP地址和用户名'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    if not password and not private_key:
        return Response({
            'success': False,
            'error': '请提供密码或私钥'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    try:
        result = get_host_info(
            ip_address=ip_address,
            port=int(port),
            username=username,
            password=password,
            private_key=private_key if private_key else None
        )
        
        if result['success']:
            return Response(result)
        else:
            return Response(result, status=status.HTTP_400_BAD_REQUEST)
    except Exception as e:
        return Response({
            'success': False,
            'error': f'获取主机信息失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
